package com.jame.basics.thread.queue;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author : Jame
 * @date : 2021-01-13 15:30
 **/
public class QueueTest {

     ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(2);



    /**
     * 抛出异常
     *
     * @throws InterruptedException
     */
    @Test
    public  void test1() throws InterruptedException {

        arrayBlockingQueue.add("a");
        arrayBlockingQueue.add("b");
        //如果满了会抛出异常
        //arrayBlockingQueue.add("c");

        //查看队首元素
        System.out.println(arrayBlockingQueue.element());

        arrayBlockingQueue.remove();
        arrayBlockingQueue.remove();
        //队列中没有内容也会抛出异常
        // arrayBlockingQueue.remove();

    }

    /**
     * 已满返回false
     * 获取为空返回null
     */
    @Test
    public  void test2() {
        //添加
        System.out.println(arrayBlockingQueue.offer("a"));
        System.out.println(arrayBlockingQueue.offer("b"));
        System.out.println(arrayBlockingQueue.offer("c"));

        //查看队首
        System.out.println(arrayBlockingQueue.peek());

        //获取
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
    }

    /**
     *
     * 阻塞添加,阻塞获取,一直等
     *
     * @throws InterruptedException
     */
    @Test
    public  void test3() throws InterruptedException {
        arrayBlockingQueue.put("a");
        arrayBlockingQueue.put("a");
       // arrayBlockingQueue.put("a");

        arrayBlockingQueue.take();
        arrayBlockingQueue.take();
        arrayBlockingQueue.take();
    }


    /**
     *  等待指定时间,如果没有在指定时间完成操作则放弃操作
      * @throws InterruptedException
     */
    @Test
    public  void test4() throws InterruptedException {
        //添加
        System.out.println(arrayBlockingQueue.offer("a"));
        System.out.println(arrayBlockingQueue.offer("b"));
        //等待两秒,如果没有位置放弃操作
        System.out.println(arrayBlockingQueue.offer("c",2, SECONDS));

        //查看队首
        System.out.println(arrayBlockingQueue.peek());

        //获取
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        //等待两秒,如果队列中没有元素放弃操作
        System.out.println(arrayBlockingQueue.poll(2, SECONDS));
    }
}

